import cv2
import numpy as np
import os

path = "C:/Users/shouw/Desktop/tmp/datasou/"
recognizer = cv2.face.LBPHFaceRecognizer_create()   # 生成LBPH识别器实例模型

def imageandLable(path):     # 获取与图片对应的标签
    '''os.listdir读取目录下所有文件名，
    os.path.join把目录下路径和文件名结合起来得到绝对路径'''
    imgePaths = [os.path.join(path,f) for f in os.listdir(path)]
    faceSample = []
    ids = []

    for imgePath in imgePaths:
        img = cv2.imread(imgePath,cv2.IMREAD_GRAYSCALE) # 读人灰度图片
        '''os.path.split()命令按照路径将文件名和路径分开，通过split拆分，
        索引[1]代表人的标签'''


        face_id = int(os.path.split(imgePath)[-1].split(".")[1])
        faceSample.append(img)
        ids.append(face_id)
    return faceSample, ids
print("训练人脸样本")
faces,ids = imageandLable(path)
recognizer.train(faces,np.array(ids))   # 训练样本集
recognizer.write('C:/Users/shouw/Desktop/tmp/trainer/trainer.yml')      # 保存模型
print("训练完毕")
